<template>
  <div class="page-classifyList">
    <filter-view @update-list="() => getAreaList()" />
    <a-table
      id="sortTable"
      :row-selection="{ selectedRowKeys: statusState.selectedRowKeys, checkStrictly: false, onChange: onSelectChange }"
      :expandRowByClick="false"
      row-key="area_id"
      :columns="columns"
      :pagination="false"
      :data-source="state.areaList"
      :loading="state.loading"
      :scroll="{ x: 1500 }"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'sort'">
          <menu-outlined />
        </template>
        <template v-else-if="column.key === 'area_name'">
          <span>
            {{ record.area_name || '-' }}
          </span>
        </template>
        <template v-else-if="column.key === 'area_video_count'">
          <span>
            {{ formatNumber(record.area_video_count) || '-' }}
          </span>
        </template>
        <template v-else-if="column.key === 'area_person_count'">
          <span>
            {{ formatNumber(record.area_person_count) || '-' }}
          </span>
        </template>
        <template v-else-if="column.key === 'action'">
          <span>
            <a class="basicColor" @click="updateArea(record)">编辑</a>
            <a-divider type="vertical" />
            <a class="basicColor" @click="deleteArea(record)"> 删除 </a>
          </span>
        </template>
      </template>
    </a-table>
    <!-- 批量导入提示消息 -->
    <modal-dialog
      title="批量导入"
      v-model:visible="tipVisible"
      okText="确定"
      cancelText=" "
      :width="458"
      @confirm="tipConfirm"
      :showSingleBtn="true"
    >
      <span class="modal-text"> <check-circle-outlined style="" />导入成功！共30条数据 </span><br />
      <span class="modal-text"> <close-circle-outlined />导入失败！请检查文件表头是否与模板一致 </span>
    </modal-dialog>
    <!-- 删除对话框 -->
    <modal-dialog
      title="提示"
      v-model:visible="deleteVisible"
      okText="确定"
      cancelText="取消"
      :width="458"
      @confirm="deleteConfirm"
      @cancel="deleteCancel"
    >
      <span>确定要删除该地区吗</span>
    </modal-dialog>
    <!-- 添加/编辑对话框 -->
    <modal-dialog
      :title="statusState.isAdd ? '添加地区' : '编辑地区'"
      v-model:visible="statusState.formVisible"
      okText="确定"
      cancelText="取消"
      :width="511"
      :afterClose="afterCloseEdit"
      @confirm="formConfirm"
      @cancel="formCancel"
    >
      <a-form ref="formRef" :model="formState" :rules="formRules">
        <a-form-item label="地区名称" name="area_name">
          <a-input
            v-model:value.trim="formState.area_name"
            :maxlength="30"
            class="w-[359px]"
            placeholder="请输入地区名称"
          />
        </a-form-item>
      </a-form>
    </modal-dialog>
    <!-- 批量导入对话框 -->
    <modal-dialog
      title="批量导入"
      class="batchBox"
      v-model:visible="statusState.batchVisible"
      okText="开始导入"
      cancelText="取消"
      :width="618"
      :afterClose="() => (templateFile = '')"
      @confirm="batchConfirm"
      @cancel="batchCancel"
    >
      <a-form>
        <a-form-item label="上传模板" name="area_name">
          <div>
            <div style="display: flex; align-items: center; height: 32px">
              <a-upload
                name="file"
                :fileList="fileList"
                :maxCount="1"
                :showUploadList="false"
                :multiple="false"
                :before-upload="beforeUpload"
                @change="handleChange"
              >
                <a-input-search v-model:value="templateFile" enter-button="上传文件" class="w-[334px]" />
              </a-upload>
              <a class="download-template" :href="`${baseUrl}v1/video/area/template`">点击下载模板</a>
            </div>
            <p class="download-introduce">
              说明：可导入Excel文件，请先下载模板，填充数据再上传，模板表头请勿修改，文件大小不能超过200M
            </p>
          </div>
        </a-form-item>
      </a-form>
    </modal-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, reactive, inject } from 'vue'
import { message } from 'ant-design-vue'
//import Sortable from 'sortablejs'
import { formatNumber } from '@/utils/format'
import FilterView from './components/FilterView.vue'
import { column } from './dataSource'
import Sortable from 'sortablejs'
import { areaState, resetState, statusState } from './state'
import type { AreaData } from '@/types/site/area'
import ModalDialog from '@/components/components/modal/ModalView.vue'
import type { UploadProps } from 'ant-design-vue'
import apis from '@/apis'
import { storage } from '@/utils/storage'
const {
  site: { area_list, area_add, area_update, area_del, area_batch_add }
} = apis
const deleteId = ref()
const fileData = ref('')
const tipVisible = ref(false)
const templateFile = ref('')
const columns = ref(column)
const deleteVisible = ref(false)
const siteId = storage.get('siteId')
const baseUrl: any = inject('baseUrl')
console.log('baseUrl123: ', baseUrl)
type Key = string
const fileList: any = ref([])
const state = reactive<{ loading: boolean; areaList: AreaData[]; copyTableData: AreaData[] }>({
  loading: false,
  areaList: [],
  copyTableData: []
})
const formRef = ref()
interface IFormState {
  area_name: string
  area_id?: string
  site_id?: string
}
//添加分类form数据
const formState = reactive<IFormState>({
  area_name: ''
})
const formRules = reactive({
  area_name: [{ required: true, message: '请输入地区名称' }]
})
const afterCloseEdit = () => {
  formRef.value.resetFields() //清除字段校验结果
}
//获取地区列表接口
const getAreaList = () => {
  state.loading = true
  areaState.site_id = siteId
  area_list(areaState)
    .then((res: any) => {
      state.areaList = res?.areas ?? []
      console.log('地区列表: ', state.areaList)
      state.loading = false
    })
    .catch(() => {
      state.loading = false
    })
}
const onSelectChange = (rowKeys: Key[]) => {
  console.log('selectedRowKeys changed: ', rowKeys)
  statusState.selectedRowKeys = rowKeys
}
//行删除
const deleteArea = (item: AreaData) => {
  deleteVisible.value = true
  console.log(statusState.selectedRowKeys, '行删除id')
  deleteId.value = item.area_id
}
//编辑
const updateArea = (item: AreaData) => {
  statusState.formVisible = true
  statusState.isAdd = false
  const { area_name, area_id } = item
  formState.area_name = area_name
  formState.area_id = area_id
}
//提示
const tipConfirm = () => {
  tipVisible.value = false
}
/**
  删除分类对话框事件
 */
const deleteConfirm = (value: any) => {
  console.log('value: ', value)
  area_del({ area_id: [deleteId.value] }).then(() => {
    message.success('地区删除成功')
    deleteVisible.value = value
    getAreaList()
  })
}
const deleteCancel = () => {
  deleteVisible.value = false
}
/**
  批量导入对话框事件
 */
const batchConfirm = (value: any) => {
  console.log('value: ', value)
  statusState.batchVisible = value
  console.log(fileData, 'fileData')
  // tipVisible.value = true
  handleUpload()
}
const batchCancel = () => {
  statusState.batchVisible = false
}
/**
  添加编辑对话框事件
 */
const formConfirm = (value: any) => {
  formRef.value.validate().then(() => {
    if (statusState.isAdd) {
      formState.site_id = siteId
      area_add(formState).then(() => {
        message.success('地区添加成功')
        statusState.formVisible = value
        getAreaList()
      })
    } else {
      area_update(formState).then(() => {
        message.success('地区编辑成功')
        statusState.formVisible = value
        getAreaList()
      })
    }
  })
}
const formCancel = () => {
  statusState.formVisible = false
  formState.area_name = ''
}
//调用排序接口
const sortFunc = (item: any) => {
  area_update({
    ...item
  }).then(() => {
    message.success('排序成功')
    getAreaList()
  })
}
//初始化表格拖动
const initSortable = () => {
  const el = document.querySelector('#sortTable tbody') as HTMLElement
  console.log({ el })
  new Sortable(el, {
    handle: '.ant-table-row',
    animation: 150,
    ghostClass: 'blue-background-class',
    forceFallback: true,
    sort: true,
    // async
    onEnd(item) {
      console.log({ item })
      if (item.newIndex === item.oldIndex) return
      const startIndex = (item.oldIndex as number) - 1
      const endIndex = (item.newIndex as number) - 1
      const { area_order, ...params } = state.areaList[startIndex]
      // const { area_order } = state.areaList[endIndex]
      sortFunc({ area_order: state.areaList[endIndex].area_order, ...params })
    }
  })
}
// 上传文件
const handleChange = (info: any) => {
  console.log('上传文件', info)
  console.log('info.fileList[0].originFileObj: ', info.fileList[0].originFileObj)
  fileList.value = [info.fileList[0].originFileObj]
}
// 上传按钮
const beforeUpload: UploadProps['beforeUpload'] = (file: any) => {
  console.log('file11111111: ', file)
  // templateFile.value = file.name
  // fileList.value = [file]
  // return false

  templateFile.value = file.name
  var fileType = file.name.split('.')
  if (
    // fileType[fileType.length - 1] === 'doc' ||
    // fileType[fileType.length - 1] === 'docx' ||
    // fileType[fileType.length - 1] === 'ppt' ||
    // fileType[fileType.length - 1] === 'pdf' ||
    // fileType[fileType.length - 1] === 'txt' ||
    fileType[fileType.length - 1] === 'xlsx'
    // fileType[fileType.length - 1] === 'xls'
  ) {
    fileList.value = [file]
    console.log('fileList.value: ', fileList.value)
    return new Promise((reject) => false)
  } else {
    // message.info('上传文件类型不支持（仅支持文本文档、PPT、PDF、表格文档）')
    message.warning('上传文件类型不支持（仅支持xlsx格式）')
    return new Promise((reject) => false)
  }
}
//开始上传
const handleUpload = () => {
  if (fileList.value.length === 0) return message.warning('请上传文件')
  const formData = new FormData()
  formData.append('file', fileList.value[0])
  formData.append('site_id', siteId)
  area_batch_add(formData).then(() => {
    message.success('批量导入成功')
    getAreaList()
  })
}

onMounted(() => {
  getAreaList()
  initSortable()
})
</script>
<style lang="less" scoped>
@basicColor: #0083ff;

:deep(.ant-upload-list) {
  display: none;
}

.modal-text {
  font-size: 16px;
  color: #595959;
}

:deep(.ant-form-item-label) {
  width: 80px;
  text-align: right;
}

:deep(.ant-form-item-label > label::after) {
  content: '';
}

.batchBox {
  .download-template {
    margin-left: 16px;
  }

  .download-introduce {
    font-size: 12px;
    color: #bfbfbf;
    margin-top: 8px;
  }
}

.page-classifyList {
  padding-top: 6px;
  box-sizing: border-box;

  :deep(.ant-table-thead > tr > th) {
    color: #262626;
    font-weight: 500;
  }

  :deep(
      .ant-table-thead
        > tr
        > th:not(:last-child):not(.ant-table-selection-column):not(.ant-table-row-expand-icon-cell):not(
          [colspan]
        )::before
    ) {
    width: 0;
  }

  :deep(.ant-table-cell .ant-table-cell-with-append) {
    display: flex;
    align-items: center;
  }

  :deep(.ellipsis-text) {
    max-width: 154px !important;
    white-space: nowrap;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    cursor: pointer;
  }

  .basicColor {
    color: @basicColor;
  }
}
</style>
